package com.rc.web.service.impl;

import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.rc.pojo.po.AdoptionInfo;
import com.rc.pojo.po.PlantItem;
import com.rc.pojo.vo.adoptionInfo.AdoptionInfoVO;
import com.rc.web.converter.AdoptionInfoConverter;
import com.rc.web.mapper.AdoptionInfoMapper;
import com.rc.web.service.AdoptionInfoService;
import com.rc.web.service.PlantItemService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 领养信息 服务层实现。
 * 提供领养信息相关的业务逻辑实现
 */
@Service
@RequiredArgsConstructor
public class AdoptionInfoServiceImpl extends ServiceImpl<AdoptionInfoMapper, AdoptionInfo> implements AdoptionInfoService {
    // 领养信息转换器
    private final AdoptionInfoConverter infoConverter;
    // 植物项服务
    private final PlantItemService plantItemService;

    /**
     * 根据订单ID获取领养信息
     * @param orderId 订单ID
     * @return 领养信息VO
     */
    @Override
    public AdoptionInfoVO getByOrderId(Long orderId) {
        AdoptionInfo adoptionInfo = this.getById(orderId);
        return infoConverter.toVO(adoptionInfo);
    }

    /**
     * 获取领养信息列表
     * @return 领养信息VO列表
     */
    @Override
    public List<AdoptionInfoVO> getList() {
        List<AdoptionInfo> list = this.list();
        return list.stream()
                .map(infoConverter::toVO)
                .toList();
    }

    /**
     * 结束领养
     * @param orderId 订单ID
     */
    @Override
    @Transactional
    public void endAdoption(Long orderId) {
        // 获取领养信息
        AdoptionInfo adoptionInfo = this.getById(orderId);

        // 更新领养状态为false
        adoptionInfo.setAdopting(false);
        this.updateById(adoptionInfo);

        // 更新植物项领养状态为false
        PlantItem plantItem = PlantItem.builder()
                .id(adoptionInfo.getPlantItemId())
                .adoption(false)
                .build();
        plantItemService.updateById(plantItem);
    }
}
